Sub UnpivotData()
    Dim wsSource As Worksheet
    Dim wsOutput As Worksheet
    Dim rng As Range
    Dim cell As Range
    Dim i As Long, j As Long
    Dim outRow As Long

    ' Get selected range
    If TypeName(Selection) <> "Range" Then
        MsgBox "Please select a valid data range before running the macro.", vbExclamation
        Exit Sub
    End If
    Set rng = Selection

    ' Create or clear output sheet
    On Error Resume Next
    Set wsOutput = Worksheets("Unpivoted Data")
    If wsOutput Is Nothing Then
        Set wsOutput = Worksheets.Add
        wsOutput.Name = "Unpivoted Data"
    Else
        wsOutput.Cells.Clear
    End If
    On Error GoTo 0

    Set wsSource = ActiveSheet

    ' Set headers
    wsOutput.Range("A1") = "Particulars"
    wsOutput.Range("B1") = "Year"
    wsOutput.Range("C1") = "Amount"
    outRow = 2

    ' Loop through rows and columns in selection
    For i = 2 To rng.Rows.Count
        For j = 2 To rng.Columns.Count
            wsOutput.Cells(outRow, 1).Value = rng.Cells(i, 1).Value                ' Particular
            wsOutput.Cells(outRow, 2).Value = rng.Cells(1, j).Value               ' Year header
            wsOutput.Cells(outRow, 3).Value = rng.Cells(i, j).Value               ' Amount
            outRow = outRow + 1
        Next j
    Next i

    MsgBox "Unpivot complete! Output is in sheet 'Unpivoted Data'.", vbInformation
End Sub
